import React, { useEffect, useMemo, useRef, useState } from 'react';
// 引入 echarts 核心模块，核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core';
// 引入柱状图图表，图表后缀都为 Chart
import {
    BarChart
} from 'echarts/charts';
// 引入提示框，标题，直角坐标系组件，组件后缀都为 Component
import {
    ToolboxComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    DataZoomComponent
} from 'echarts/components';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import {
    CanvasRenderer
} from 'echarts/renderers';
import Base from './base';
import $ from 'jquery';

// 注册必须的组件
echarts.use(
    [
        ToolboxComponent,
        TooltipComponent,
        GridComponent,
        DataZoomComponent,
        LegendComponent,
        BarChart,
        CanvasRenderer
    ]
);

const labelOption = {
    show: true,
    rotate: 90,
    align: 'left',
    verticalAlign: 'middle',
    position: 'insideBottom',
    distance: 15,
    formatter: '{name|{a}} {c}',
    fontSize: 28,
    rich: {
        name: {}
    }
};

const setEcharts = (obj, property, ele, dataList) => {
    let width = 0;
    const series = [];
    const xdata = [];
    const legendData = dataList.length > 0 ? typeof property.legendNames === 'string' ? property.legendNames.split(',') : property.legendNames : [];
    const yNames = typeof property.yNames === 'string' ? property.yNames.split(',') : property.yNames;

    const seriesData = {};

    dataList.forEach(d => {
        xdata.push(d[property.xName]);

        yNames.forEach(n => {
            if (!seriesData[n]) seriesData[n] = [];
            seriesData[n].push(d[n]);
        });
    });

    for (let i = 0; i < yNames.length; i++) {
        const n = yNames[i];
        series.push({
            name: legendData[i],
            type: 'bar',
            barGap: 0,
            label: labelOption,
            emphasis: {
                focus: 'series'
            },
            barWidth: 60,
            data: seriesData[n]
        });
    }

    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        grid: {
            left: '40px',
            right: '40px',
            bottom: '40px',
            top: '40px'
        },
        legend: {
            data: legendData,
            textStyle: {
                fontSize: 28,
            }
        },
        toolbox: {
            show: false,
            orient: 'vertical',
            left: 'right',
            top: 'center',
            feature: {
                mark: { show: true },
                dataView: { show: true, readOnly: false },
                magicType: { show: true, type: ['line', 'bar', 'stack'] },
                restore: { show: true },
                saveAsImage: { show: true }
            }
        },
        xAxis: [
            {
                type: 'category',
                axisTick: { show: false },
                data: xdata,
                axisLabel: {
                    fontSize: 28,
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                axisLabel: {
                    fontSize: 20,
                }
            }
        ],
        series
    };

    width = yNames.length * 24 + 32;
    if (width < 160) width = 160;
    width = width * xdata.length;

    const p = property.scrollTypeProperty;
    const pw = $(ele).parent().width();
    if (pw > width) {
        ele.style.width = '100%';
        p && p.setIsVisible && p.setIsVisible(false);
    }
    else {
        if (p) {
            p.setIsVisible && p.setIsVisible(true);
            p.isVisible = true;
            p.valueChange = () => property.setRefresh();
        }
        if (p && p.getValue && parseInt(p.getValue()) === 2) {
            option.dataZoom = [{
                type: 'slider',
                show: true,
                realtime: true,
                start: 0,
                end: 40,

            }];
            ele.style.width = '100%';
        }
        else ele.style.width = width + 'px';
    }

    if (obj.chart) obj.chart.dispose();
    obj.chart = echarts.init(ele);
    obj.chart.setOption(option);
};

export default React.memo((props) => {
    const { property } = Base.getProps(props);
    const [isVisible, setIsVisible] = useState(property.isVisible !== false);
    const [dataList, setDataList] = useState(property.dataList || []);
    const obj = useMemo(() => ({}), []);

    const div = useRef(null);

    useEffect(() => {
        if (div.current) {
            setEcharts(obj, property, div.current, dataList);
        }
    }, [obj, div, dataList, property]);

    property.setVisible = (v) => setIsVisible(v);
    property.setDataList = (d) => setDataList(d);
    property.setRefresh = () => setEcharts(obj, property, div.current, dataList);

    if (!isVisible) return null;

    return <div className={property.className} style={property.style}>
        <div style={{ height: '100%' }} ref={div}></div>
    </div>;
});